<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/2/7
 * Time: 23:54
 */
declare(strict_types=1);

namespace App\Service;
use App\Model\Dao\MchAccountAccessDao;
use App\Model\Dao\MchAccountAccessDetailDao;
use App\Model\Dao\MchAccountDao;
use App\Model\Dao\RateSettleDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderDisDao;
use App\Utils\CustomUtils;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Exception;

/**
 * Class SettleTradeOrderDisLookIntoService
 * @package App\Service
 * 交易订单拒付调查调查费结算
 */
class SettleTradeOrderDisLookIntoService extends CommonService
{

    /**
     * @Inject()
     * @var TradeOrderDisDao
     */
    private $TradeOrderDisDao;

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var MchAccountDao
     */
    private $MchAccountDao;

    /**
     * @Inject()
     * @var MchAccountAccessDao
     */
    private $MchAccountAccessDao;

    /**
     * @Inject()
     * @var MchAccountAccessDetailDao
     */
    private $MchAccountAccessDetailDao;

    /**
     * @Inject()
     * @var RateSettleDao
     */
    private $RateSettleDao;

    public function handle($param) {
        // 校验
        $tradeOrderDis = $this->TradeOrderDisDao->get($param['disId']);
        if(!$tradeOrderDis) {
            throw new Exception('拒付单不存在，终止处理', FAILED_CODE);
        }
        if($tradeOrderDis['handleStatus'] != $param['handleStatus']) {
            throw new Exception('拒付单处理状态不对应', FAILED_CODE);
        }
        if($tradeOrderDis['settleStatus'] == 1) {
            throw new Exception('拒付单已冻结结算完成', FAILED_CODE);
        }
        $tradeOrder = $this->TradeOrderDetailDao->get($tradeOrderDis['orderId']);
        if($tradeOrder['isSettle'] != 2) {
            throw new Exception('拒付单原始交易订单未结算', FAILED_CODE);
        }
        $mchAccount = $this->MchAccountDao->get($param['mchAccountId']);
        if(!$mchAccount) {
            throw new Exception('查询账户记录失败', FAILED_CODE);
        }
        $isDetail = $this->MchAccountAccessDetailDao->getWhere([
            "disId" => $tradeOrderDis['id'],
            "type"     => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CASH_OUT,
        ]);

        if ($param['handleStatus'] == 0) {
            if ($isDetail && empty($isDetail['accessId'])) {
                throw new Exception('交易拒付单已冻结结算', FAILED_CODE);
            }
            return $this->handleAdd($param, $tradeOrder, $tradeOrderDis, $mchAccount);
        } else {
            // 初审通过不用管
            if ($param['handleStatus'] == 1) {
                return $this->handleFirstConfirm($tradeOrderDis);
            }
            if ($isDetail && !empty($isDetail['accessId'])) {
                throw new Exception('交易拒付单请先发起冻结结算', FAILED_CODE);
            }
            return $this->handleConfirm($param, $tradeOrder, $tradeOrderDis, $mchAccount);
        }
        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易订单拒付调查结算成功");
    }

    private function handleFirstConfirm($tradeOrderDis) {
        Db::beginTransaction();
        try {
            $this->TradeOrderDisDao->set($tradeOrderDis['id'], [
                'settleStatus'  => 1,
            ]);

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();
            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易订单拒付调查初审结算失败");
        }
        Db::commit();
        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易订单拒付调查初审通过结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrder
     * @param $tradeOrderDis
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 新增拒付记录，出入账
     */
    public function handleAdd($param, $tradeOrder, $tradeOrderDis, $mchAccount) {


        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transSettleAmount = $tradeOrderDis['transSettleAmount'];

        // 交易可提现金额 余额前后
        $beforeTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterTradeCashAmount  = $mchAccount['tradeCashAmount'] - $transSettleAmount;

        // 交易冻结金额 余额前后
        $beforeTradeFrozenAmount = $mchAccount['tradeFrozenAmount'];
        $afterTradeFrozenAmount = $mchAccount['tradeFrozenAmount'] + $transSettleAmount;

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.可提现出账
            // 2.可提现入账
            // 3.更新订单结算状态
            // 4.更新账户
            $this->handleCashOutTransAmount($param, $tradeOrderDis, $mchAccount, $transSettleAmount, $beforeTradeCashAmount, $afterTradeCashAmount);

            $this->handleFrozenInTransAmount($param, $tradeOrderDis, $mchAccount, $transSettleAmount, $beforeTradeFrozenAmount, $afterTradeFrozenAmount);

            $updateTradeOrderDis = array(
                'settleStatus' => 1
            );
            $this->TradeOrderDisDao->update($param['disId'], $updateTradeOrderDis);

            $updateMchAccount = array(
                "tradeCashAmount"   => $afterTradeCashAmount,
                "tradeFrozenAmount" => $afterTradeFrozenAmount,
                "updateVersion"     => $updateVersion
            );
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }
        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易拒付单结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易拒付单结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrder
     * @param $tradeOrderDis
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 拒付单，审核，出入账
     */
    private function handleConfirm($param, $tradeOrder, $tradeOrderDis, $mchAccount) {
        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transSettleAmount = $tradeOrderDis['transSettleAmount'];

        // 交易可提现金额，解冻金额，余额前后
        $beforeFrozenTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterFrozenTradeCashAmount  = $mchAccount['tradeCashAmount'] + $transSettleAmount;

        // 交易冻结金额，解冻金额，余额前后
        $beforeFrozenTradeFrozenAmount = $mchAccount['tradeFrozenAmount'];
        $afterFrozenTradeFrozenAmount = $mchAccount['tradeFrozenAmount'] - $transSettleAmount;

        // 交易可提现金额，出账，余额前后
        $beforeDisTradeCashAmount = $afterFrozenTradeCashAmount;
        $afterDisTradeCashAmount  = $afterFrozenTradeCashAmount - $transSettleAmount;

        // 交易可提现金额，扣拒付手续费，余额前后
        $disLookIntoFee = 0;
        $beforeDisFeeTradeCashAmount = 0;
        $afterDisFeeTradeCashAmount  = 0;
        if ($param['handleStatus'] == 3) {
            $rateSettle = $this->RateSettleDao->getByMchId($tradeOrder['mchId']);
            if(!$rateSettle) {
                throw new Exception('查询商户结算费率失败', FAILED_CODE);
            }
            $disLookIntoFee = $rateSettle['disLookIntoFee'];
            $beforeDisFeeTradeCashAmount = $afterDisTradeCashAmount;
            $afterDisFeeTradeCashAmount = $beforeDisFeeTradeCashAmount - $disLookIntoFee;
        }

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.解冻交易冻结出账
            // 2.解冻交易可提现入账
            // 3.复审成功，交易可提现出账
            // 4.复审成功，新增拒付手续费
            // 5.更新拒付订单结算状态
            // 6.复审成功，才会更新订单拒付金额，拒付结算金额
            // 7.更新账户

            // step 1
            $accessId = $this->handleConfirmFrozenOutTransAmount($param, $tradeOrderDis, $mchAccount, $transSettleAmount, $beforeFrozenTradeFrozenAmount, $afterFrozenTradeFrozenAmount);

            // handleAdd新增时添加的记录，查询
            $frozenInDetail = $this->MchAccountAccessDetailDao->getWhere(['disId'  => $tradeOrderDis['id'], 'type' => TYPE_TRADE_ORDER_DIS_LOOK_INTO_FROZEN_IN]);

            $this->MchAccountAccessDetailDao->update($frozenInDetail['id'], ['accessId' => $accessId]);

            // step 2
            $confirmCashInId = $this->handleConfirmCashInTransAmount($param, $tradeOrderDis, $mchAccount, $transSettleAmount, $beforeFrozenTradeCashAmount, $afterFrozenTradeCashAmount);

            if ($param['handleStatus'] == 3) {
                // step 3
                $accessId = $this->handleConfirmCashOutTransAmount($param, $tradeOrderDis, $mchAccount, $transSettleAmount, $beforeDisTradeCashAmount, $afterDisTradeCashAmount);

                $this->MchAccountAccessDetailDao->update($confirmCashInId, ['accessId' => $accessId]);

                // handleAdd新增时添加的记录，查询
                $cashOutDetail = $this->MchAccountAccessDetailDao->getWhere(['disId'  => $tradeOrderDis['id'], 'type' => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CASH_OUT]);

                $this->MchAccountAccessDetailDao->update($cashOutDetail['id'], ['accessId' => $accessId]);

                // step 4
                $this->handleConfirmDisLookIntoFee($param, $tradeOrderDis, $mchAccount, $disLookIntoFee, $beforeDisFeeTradeCashAmount, $afterDisFeeTradeCashAmount);
            }

            // step 5
            $this->TradeOrderDisDao->set($tradeOrderDis['id'], [
                'settleStatus'              => 1,
                'disLookIntoFeeSettleTime'  => time()
            ]);

            // 审核成功
            if ($param['handleStatus'] == 3) {
                // step 6
                $this->TradeOrderDetailDao->set($tradeOrder['id'], [
                    'disLookIntoFee'     => $disLookIntoFee
                ]);

                // step 7
                $updateMchAccount = array(
                    "tradeCashAmount"   => $afterDisFeeTradeCashAmount,
                    "tradeFrozenAmount" => $afterFrozenTradeFrozenAmount,
                    "updateVersion"     => $updateVersion
                );
            } else {

                // step 7
                $updateMchAccount = array(
                    "tradeCashAmount"   => $afterFrozenTradeCashAmount,
                    "tradeFrozenAmount" => $afterFrozenTradeFrozenAmount,
                    "updateVersion"     => $updateVersion
                );
            }
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易拒付单审核结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易拒付单审核结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，拒付金额，可提现出账
     */
    private function handleCashOutTransAmount($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "orderId"           => $tradeOrderDis['orderId'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "remark"            => "交易订单拒付调查冻结可提现账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 提交记录，拒付金额，冻结金额入账
     */
    private function handleFrozenInTransAmount($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH_FROZEN,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_FROZEN_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "orderId"           => $tradeOrderDis['orderId'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "remark"            => "交易订单拒付调查冻结冻结账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，拒付金额，可提现入账
     */
    private function handleConfirmCashInTransAmount($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CONFIRM_CASH_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "orderId"           => $tradeOrderDis['orderId'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "remark"            => "交易订单拒付调查冻结可提现账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccessDetail['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 确认，拒付金额，冻结金额出账
     */
    private function handleConfirmFrozenOutTransAmount($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderDis["mchId"],
            "mchNo"        => $tradeOrderDis["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_DIS_LOOK_INTO,
            "accountType"  => ACCOUNT_TYPE_CASH_FROZEN,
            "orderId"      => $tradeOrderDis['orderId'],
            "tradeNo"      => $tradeOrderDis['tradeNo'],
            "disId"        => $tradeOrderDis['id'],
            "amount"       => 0,
            "currency"     => $tradeOrderDis['transSettleCurrency'],
            "status"       => 1,
            "isShow"       => 0,
            "remark"       => "交易订单拒付调查",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH_FROZEN,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CONFIRM_FROZEN_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "orderId"           => $tradeOrderDis['orderId'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "remark"            => "交易订单拒付调查解冻冻结账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * @return string
     * 审核，拒付金额，可提现出账，拒付成功
     */
    private function handleConfirmCashOutTransAmount($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderDis["mchId"],
            "mchNo"        => $tradeOrderDis["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_DIS_LOOK_INTO,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "orderId"      => $tradeOrderDis['orderId'],
            "tradeNo"      => $tradeOrderDis['tradeNo'],
            "disId"        => $tradeOrderDis['id'],
            "amount"       => -$amount,
            "currency"     => $tradeOrderDis['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单拒付调查",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CONFIRM_CASH_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "orderId"           => $tradeOrderDis['orderId'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "remark"            => "交易订单拒付调查",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
        return $mchAccountAccess['id'];
    }

    /**
     * @param $param
     * @param $tradeOrderDis
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 拒付手续费出账
     */
    private function handleConfirmDisLookIntoFee($param, $tradeOrderDis, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderDis["mchId"],
            "mchNo"        => $tradeOrderDis["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_DIS_LOOK_INTO,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "orderId"      => $tradeOrderDis['orderId'],
            "tradeNo"      => $tradeOrderDis['tradeNo'],
            "disId"        => $tradeOrderDis['id'],
            "amount"       => -$amount,
            "currency"     => $tradeOrderDis['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单拒付调查费出账",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderDis["mchId"],
            "mchNo"             => $tradeOrderDis["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_DIS_LOOK_INTO_CONFIRM_DIS_FEE_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "orderId"           => $tradeOrderDis['id'],
            "tradeNo"           => $tradeOrderDis['tradeNo'],
            "disId"             => $tradeOrderDis['id'],
            "currency"          => $tradeOrderDis['transSettleCurrency'],
            "remark"            => "交易订单拒付调查费出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

}